<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>throw 表达式</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/throw","wgTitle":"cpp/language/throw","wgCurRevisionId":73226,"wgArticleId":2759,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/throw","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><style type="text/css">/*<![CDATA[*/
.source-text {line-height: normal;}
.source-text li, .source-text pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for text
 * CSS class: source-text, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.text.source-text .de1, .text.source-text .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.text.source-text  {font-family:monospace;}
.text.source-text .imp {font-weight: bold; color: red;}
.text.source-text li, .text.source-text .li1 {font-weight: normal; vertical-align:top;}
.text.source-text .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.text.source-text .li2 {font-weight: bold; vertical-align:top;}
.text.source-text .ln-xtra, .text.source-text li.ln-xtra, .text.source-text div.ln-xtra {background-color: #ffc;}
.text.source-text span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_throw skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">throw 表达式</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../container.html" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp">异常</a><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <strong class="selflink">throw 表达式</strong></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="function-try-block.html" title="cpp/language/function-try-block">函数 try 块</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="try_catch.html" title="cpp/language/try catch">try/catch 块</a></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="noexcept_spec.html" title="cpp/language/noexcept spec"><code>noexcept</code> 说明符</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="noexcept.html" title="cpp/language/noexcept"><code>noexcept</code> 运算符</a><span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"> <a href="except_spec.html" title="cpp/language/except spec">动态异常说明</a><span class="t-mark-rev t-until-cxx17">(C++17 前)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>对错误条件发信号，并执行错误处理代码。
</p>
<h3><span class="mw-headline" id=".E8.AF.AD.E6.B3.95">语法</span></h3>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>throw</b></code> <span class="t-spar">表达式</span>
</td>
<td> (1)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>throw</b></code>
</td>
<td> (2)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<h3><span class="mw-headline" id=".E8.A7.A3.E9.87.8A">解释</span></h3>
<dl><dd><span style="font-size:0.7em; line-height:130%">更多关于 <i>try</i> 与 <i>catch</i>（异常处理）块的信息见 <a href="try_catch.html" title="cpp/language/try catch">try-catch 块</a></span> 
</dd></dl>
<div class="t-li1"><span class="t-li">1)</span> 首先，从 <span class="t-spar">表达式</span> <a href="copy_initialization.html" title="cpp/language/copy initialization">复制初始化</a><i>异常对象</i>：
<ul><li> 这可能调用右值表达式的移动构造函数
</li></ul>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<ul><li> 这也可能会通过如 <a href="return.html" title="cpp/language/return">return 语句</a>中一般的二步重载决议调用左值表达式的移动构造函数，如果它们指名局部变量或是函数或 catch 子句的形参，且它的作用域不会超出最内层的外围 try 块（如果存在）
</li></ul>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<ul><li> 复制/移动可能会被<a href="copy_elision.html" title="cpp/language/copy elision">复制消除</a>处理
</li></ul>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx14"><td>
<ul><li> 即使复制初始化选择了移动构造函数，从左值复制初始化仍必须为良式，且析构函数必须可访问
</li></ul>
</td>
<td><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></td></tr>
</table></div>
<dl><dd> 然后转移控制给拥有匹配类型，所在的复合语句或成员初始化器列表是最近进入，且未由此执行线程退出的<a href="try_catch.html" title="cpp/language/try catch">异常处理块</a>。
</dd></dl>
<div class="t-li1"><span class="t-li">2)</span> 重抛当前处理的异常。中止当前 catch 块的执行并将控制转移到下一个匹配的异常处理块（但不是到同一个 try 块的下个 catch 子句：它所在的复合语句被认为已经‘退出’），并重用既存的异常对象：不会生成新对象。此形式只能在异常处理过程中使用（其他情况中使用时将调用 <span class="t-lc"><a href="../error/terminate.html" title="cpp/error/terminate">std::terminate</a></span>）。对于构造函数，关联到<a href="function-try-block.html" title="cpp/language/function-try-block">函数 try 块</a> 的 catch 子句必须通过重抛出退出。</div>
<p>关于在异常处理期间引发错误，见 <span class="t-lc"><a href="../error/terminate.html" title="cpp/error/terminate">std::terminate</a></span><span class="t-rev-inl t-until-cxx17"><span> 与 <span class="t-lc"><a href="../error/exception/unexpected.html" title="cpp/error/unexpected">std::unexpected</a></span></span> <span><span class="t-mark-rev t-until-cxx17">(C++17 前)</span></span></span>。
</p>
<h3><span class="mw-headline" id=".E5.BC.82.E5.B8.B8.E5.AF.B9.E8.B1.A1">异常对象</span></h3>
<p>异常对象是由 <code>throw</code> 表达式在未指明的存储中构造的临时对象。
</p><p><i>异常对象</i>的类型是除去顶层 <a href="cv.html" title="cpp/language/cv">cv 限定符</a>的 <span class="t-spar">表达式</span> 的静态类型。数组与函数类型分别调整到指针和函数指针类型。如果异常对象的类型是<a href="incomplete_type.html#.E4.B8.8D.E5.AE.8C.E6.95.B4.E7.B1.BB.E5.9E.8B" title="cpp/language/type">不完整类型</a>或除了指向（可有 cv 限定的）void 的指针以外的不完整类型的指针，那么该 throw 表达式会导致编译时错误。如果 <span class="t-spar">表达式</span> 的类型是类类型，那么它的复制/移动构造函数和析构函数必须可以访问，纵使发生<a href="copy_elision.html" title="cpp/language/copy elision">复制消除</a>也是如此。
</p><p>与其他临时对象不同，异常对象在初始化 catch 子句形参时被认为是左值，所以它可以用左值引用捕获、修改及重抛。
</p><p>异常对象持续到最后一条不以重抛而退出的 catch 子句（如果不以重抛而退出，那么它紧跟 catch 子句的形参销毁之后被销毁），或持续到引用此对象的最后一个 <span class="t-lc"><a href="../error/exception_ptr.html" title="cpp/error/exception ptr">std::exception_ptr</a></span> 被销毁（此时异常对象正好在 <span class="t-lc"><a href="../error/exception_ptr.html" title="cpp/error/exception ptr">std::exception_ptr</a></span> 的析构函数返回前被销毁）。
</p>
<h3><span class="mw-headline" id=".E6.A0.88.E5.9B.9E.E6.BA.AF">栈回溯</span></h3>
<p>异常对象构造完成时，控制流立即反向（沿调用栈向上）直到它抵达一个 <a href="try_catch.html" title="cpp/language/try catch">try 块</a>的起点，在该点按出现顺序将它每个关联的 <code>catch</code> 块的形参和异常对象的类型进行比较，以找到一个匹配（此过程的细节见 <a href="try_catch.html" title="cpp/language/try catch">try-catch</a>）。如果找不到匹配，那么控制流继续回溯栈直到下个 <code>try</code> 块，以此类推。如果找到匹配，那么控制流跳到匹配的 <code>catch</code> 块。
</p><p>因为控制流沿调用栈向上移动，所以它会为自进入相应 try 块之后的所有具有<a href="storage_duration.html" title="cpp/language/storage duration">自动存储期</a>的已构造但尚未销毁的对象，以其构造函数完成的逆序调用析构函数。<span class="t-rev-inl t-since-cxx14"><span>当从 <a href="return.html" title="cpp/language/return">return</a> 语句所使用的局部变量或临时量的构造函数中抛出异常时，从函数返回的对象的析构函数也会被调用。</span> <span><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></span></span>
</p><p>如果异常从某个对象的构造函数或（罕见地）从析构函数抛出（不管该对象的存储期），那么就会对所有已经完整构造的非静态<span class="t-rev-inl t-until-cxx14"><span>非变体</span> <span><span class="t-mark-rev t-until-cxx14">(C++14 前)</span></span></span>成员和基类以构造函数完成的逆序调用析构函数。<span class="t-rev-inl t-since-cxx14"><span>联合体式的类的变体成员只会在从构造函数中回溯的情况中销毁，且如果初始化与销毁之间改变了活动成员，那么行为未定义。</span> <span><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></span></span>
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx11"><td>
<p>如果委托构造函数在非委托构造函数成功完成前以异常退出，那么调用此对象的析构函数。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx11">(C++11 起)</span></td></tr>
</table>
<p>如果从 <a href="new.html" title="cpp/language/new">new 表达式</a>所调用的构造函数抛出异常，那么调用匹配的<a href="../memory/new/operator_delete.html" title="cpp/memory/new/operator delete">解分配函数</a>，如果它可用。
</p><p>此过程被称为<i>栈回溯（stack unwinding）</i>。
</p><p>如果由栈回溯机制所直接调用的函数在异常对象初始化后且在异常处理块开始执行前以异常退出，那么就会调用 <span class="t-lc"><a href="../error/terminate.html" title="cpp/error/terminate">std::terminate</a></span>。这种函数包括退出作用域的具有自动存储期的对象的<a href="destructor.html" title="cpp/language/destructor">析构函数</a>，和为初始化以值捕获的实参而调用（如果没有被<a href="copy_elision.html" title="cpp/language/copy elision">消除</a>）的异常对象的复制构造函数。
</p><p>如果异常被抛出但未被捕获，包括从 <span class="t-lc"><a href="../thread/thread.html" title="cpp/thread/thread">std::thread</a></span> 的启动函数，main 函数，及任何静态或线程局部对象的构造函数或析构函数中脱离的异常，那么就会调用 <span class="t-lc"><a href="../error/terminate.html" title="cpp/error/terminate">std::terminate</a></span>。是否对未捕获的异常进行任何栈回溯是由实现定义的。
</p>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<p>在重抛异常时，必须使用第二个形式，以避免异常对象使用继承的（典型）情况中发生对象切片：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">try</span> <span class="br0">{</span>
    <a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a><span class="br0">(</span><span class="st0">"abc"</span><span class="br0">)</span>.<span class="me1">substr</span><span class="br0">(</span><span class="nu0">10</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 抛出 std::length_error</span>
<span class="br0">}</span> <span class="kw1">catch</span><span class="br0">(</span><span class="kw4">const</span> <a href="../error/exception.html"><span class="kw764">std::<span class="me2">exception</span></span></a><span class="sy3">&amp;</span> e<span class="br0">)</span> <span class="br0">{</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> e.<span class="me1">what</span><span class="br0">(</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
<span class="co1">//  throw e; // 复制初始化一个 std::exception 类型的新异常对象</span>
    <span class="kw1">throw</span><span class="sy4">;</span>   <span class="co1">// 重抛 std::length_error 类型的异常对象</span>
<span class="br0">}</span></pre></div></div>
<p>throw 表达式被归类为 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">void</span></span></span> 类型的<a href="value_category.html" title="cpp/language/value category">纯右值表达式</a>。与任何其他表达式一样，它可以是另一表达式中的子表达式，在<a href="operator_other.html#.E6.9D.A1.E4.BB.B6.E8.BF.90.E7.AE.97.E7.AC.A6" title="cpp/language/operator other">条件运算符</a>中最常见：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw4">double</span> f<span class="br0">(</span><span class="kw4">double</span> d<span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">return</span> d <span class="sy1">&gt;</span> <span class="nu19">1e7</span> <span class="sy4">?</span> <span class="kw1">throw</span> <a href="../error/overflow_error.html"><span class="kw772">std::<span class="me2">overflow_error</span></span></a><span class="br0">(</span><span class="st0">"too big"</span><span class="br0">)</span> <span class="sy4">:</span> d<span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span>  
<span class="br0">{</span>
    <span class="kw1">try</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> f<span class="br0">(</span><span class="nu19">1e10</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    <span class="br0">}</span> <span class="kw1">catch</span> <span class="br0">(</span><span class="kw4">const</span> <a href="../error/overflow_error.html"><span class="kw772">std::<span class="me2">overflow_error</span></span></a><span class="sy3">&amp;</span> e<span class="br0">)</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> e.<span class="me1">what</span><span class="br0">(</span><span class="br0">)</span> <span class="sy1">&lt;&lt;</span> <span class="st0">'<span class="es1">\n</span>'</span><span class="sy4">;</span>
    <span class="br0">}</span>
<span class="br0">}</span></pre></div></div>
<h3><span class="mw-headline" id=".E5.85.B3.E9.94.AE.E8.AF.8D">关键词</span></h3>
<p><a href="../keyword/throw.html" title="cpp/keyword/throw"><tt>throw</tt></a>
</p>
<h3><span class="mw-headline" id=".E7.A4.BA.E4.BE.8B">示例</span></h3>
<div class="t-example"><div class="t-example-live-link"><div class="coliru-btn coliru-btn-run-init">运行此代码</div></div>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co2">#include &lt;iostream&gt;</span>
<span class="co2">#include &lt;stdexcept&gt;</span>
 
<span class="kw1">struct</span> A
<span class="br0">{</span>
    <span class="kw4">int</span> n<span class="sy4">;</span>
    A<span class="br0">(</span><span class="kw4">int</span> n <span class="sy1">=</span> <span class="nu0">0</span><span class="br0">)</span><span class="sy4">:</span> n<span class="br0">(</span>n<span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"A("</span> <span class="sy1">&lt;&lt;</span> n <span class="sy1">&lt;&lt;</span> <span class="st0">") 已成功构造<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
    ~A<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"A("</span> <span class="sy1">&lt;&lt;</span> n <span class="sy1">&lt;&lt;</span> <span class="st0">") 已摧毁<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> foo<span class="br0">(</span><span class="br0">)</span>
<span class="br0">{</span>
    <span class="kw1">throw</span> <a href="../error/runtime_error.html"><span class="kw770">std::<span class="me2">runtime_error</span></span></a><span class="br0">(</span><span class="st0">"错误"</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="kw1">struct</span> B
<span class="br0">{</span>
    A a1, a2, a3<span class="sy4">;</span>
    B<span class="br0">(</span><span class="br0">)</span> <span class="kw1">try</span> <span class="sy4">:</span> a1<span class="br0">(</span><span class="nu0">1</span><span class="br0">)</span>, a2<span class="br0">(</span>foo<span class="br0">(</span><span class="br0">)</span><span class="br0">)</span>, a3<span class="br0">(</span><span class="nu0">3</span><span class="br0">)</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"B 已成功构造<span class="es1">\n</span>"</span><span class="sy4">;</span>
    <span class="br0">}</span> <span class="kw1">catch</span><span class="br0">(</span>...<span class="br0">)</span> <span class="br0">{</span>
    	<a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"B::B() 因异常退出<span class="es1">\n</span>"</span><span class="sy4">;</span>
    <span class="br0">}</span>
    ~B<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"B 已摧毁<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw1">struct</span> C <span class="sy4">:</span> A, B
<span class="br0">{</span>
    C<span class="br0">(</span><span class="br0">)</span> <span class="kw1">try</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"C::C() 已成功完成<span class="es1">\n</span>"</span><span class="sy4">;</span>
    <span class="br0">}</span> <span class="kw1">catch</span><span class="br0">(</span>...<span class="br0">)</span> <span class="br0">{</span>
        <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"C::C() 因异常退出<span class="es1">\n</span>"</span><span class="sy4">;</span>
    <span class="br0">}</span>
    ~C<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"C 已摧毁<span class="es1">\n</span>"</span><span class="sy4">;</span> <span class="br0">}</span>
<span class="br0">}</span><span class="sy4">;</span>
 
<span class="kw4">int</span> main <span class="br0">(</span><span class="br0">)</span> <span class="kw1">try</span>
<span class="br0">{</span>
    <span class="co1">// 创建 A 基类子对象</span>
    <span class="co1">// 创建 B 的成员 a1</span>
    <span class="co1">// 创建 B 的成员 a2 失败</span>
    <span class="co1">// 回溯销毁 B 的 a1 成员</span>
    <span class="co1">// 回溯销毁 A 基类子对象</span>
    C c<span class="sy4">;</span>
<span class="br0">}</span> <span class="kw1">catch</span> <span class="br0">(</span><span class="kw4">const</span> <a href="../error/exception.html"><span class="kw764">std::<span class="me2">exception</span></span></a><span class="sy3">&amp;</span> e<span class="br0">)</span> <span class="br0">{</span>
    <a href="../io/cout.html"><span class="kw1758">std::<span class="me2">cout</span></span></a> <span class="sy1">&lt;&lt;</span> <span class="st0">"main() 创建 C 失败，原因："</span> <span class="sy1">&lt;&lt;</span> e.<span class="me1">what</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span></pre></div></div>
<p>输出：
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="text source-text"><pre class="de1">A(0) 已成功构造
A(1) 已成功构造
A(1) 已摧毁
B::B() 因异常退出
A(0) 已摧毁
C::C() 因异常退出
main() 创建 C 失败，原因：错误</pre></div></div> 
</div>
<h3><span class="mw-headline" id=".E7.BC.BA.E9.99.B7.E6.8A.A5.E5.91.8A">缺陷报告</span></h3>
<p>下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
</p>
<table class="dsctable" style="font-size:0.8em">
<tr>
<th> DR
</th>
<th> 应用于
</th>
<th> 出版时的行为
</th>
<th> 正确行为
</th></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue1863">CWG 1863</a>
</td>
<td> C++14
</td>
<td> 在抛出时对仅移动异常对象不要求复制构造函数，但允许之后复制
</td>
<td> 要求复制构造函数
</td></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue1866">CWG 1866</a>
</td>
<td> C++14
</td>
<td> 从构造函数栈回溯时会泄露变体成员
</td>
<td> 变体成员被销毁
</td></tr>
<tr>
<td> <a rel="nofollow" class="external text" href="https://wg21.cmeerw.net/cwg/issue2176">CWG 2176</a>
</td>
<td> C++14
</td>
<td> 从局部变量的析构函数抛出时会跳过返回值的析构函数
</td>
<td> 添加函数返回值到回溯过程
</td></tr></table>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<ul><li> <a href="try_catch.html" title="cpp/language/try catch"> try-catch 块</a>
</li><li> <a href="noexcept_spec.html" title="cpp/language/noexcept spec"> noexcept 说明符</a>
</li><li> <a href="except_spec.html" title="cpp/language/except spec">异常说明</a>
</li></ul>

<!-- 
NewPP limit report
Preprocessor visited node count: 1735/1000000
Preprocessor generated node count: 5077/1000000
Post‐expand include size: 33199/2097152 bytes
Template argument size: 9818/2097152 bytes
Highest expansion depth: 15/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:2759-0!*!0!!zh!*!zh!* and timestamp 20211215040159 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/throw&amp;oldid=73226">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/throw&amp;oldid=73226</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/throw">Online version</a></li><li>Offline version retrieved 2022-01-01 00:37.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2021年12月14日 (星期二) 18:44。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过35,760次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.076 secs. -->
	</body>
<!-- Cached 20211215193221 -->
</html>